﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Strongkeep.Model.Util
{
	/// <summary>
	/// 
	/// </summary>
	public static class DDILoader
	{
		/// <summary>
		/// 
		/// </summary>
		/// <param name="root"></param>
		/// <returns></returns>
		private static IEnumerable<DDIStatContainer> GetStats(XElement root)
		{
			var q =
				from element in root.Descendants("Stat")
				select new DDIStatContainer
				{
					Attribute = element.Attribute("name").Value,
					Value = element.Attribute("value").Value
				};

			return q;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="root"></param>
		/// <returns></returns>
		private static IEnumerable<DDIStatContainer> GetPowers(XElement root)
		{
			throw new NotImplementedException();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public static IEnumerable<DDIStatContainer> Load(string path)
		{
			XElement root = XElement.Load(path);

			var q = GetStats(root);
			//q.Concat(GetPowers(root));

			return q;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public static List<Character> Load2(string path)
		{
			Dictionary<string, int> stats = new Dictionary<string, int>();

			XElement root = XElement.Load(path);


			var result =
				from element in root.Descendants("Stat")
				//orderby element.Attribute("name").Value
				select new
				{
					Key = element.Attribute("name").Value.ToLower(),
					Value = int.Parse(element.Attribute("value").Value)
				};

			foreach (var obj in result) {
				stats.Add(obj.Key, obj.Value);
			}

			string sheetVersion = root.Attribute("Version").Value;
			bool legalCharacter = root.Attribute("legality").Value.Equals("rules-legal");

			Character character = new PlayerCharacter();
			character.Name = root.Descendants("Details").First().Element("name").Value.Trim();
			character.CharacterLevel = stats["level"];

			character.Strength = stats["strength"];
			character.Constitution = stats["constitution"];
			character.Dexterity = stats["dexterity"];
			character.Intelligence = stats["intelligence"];
			character.Wisdom = stats["wisdom"];
			character.Charisma = stats["charisma"];

			character.ArmorClass = stats["ac"];
			character.Fortitude = stats["fortitude defense"];
			character.Reflex = stats["reflex defense"];
			character.Will = stats["will defense"];

			character.HitPoints = stats["hit points"];
			character.Initiative = stats["initiative"];

			return new List<Character>() { character };
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public static List<Character> Auto()
		{
			return Load2("file://d:/hilton/strongkeep/ficha_isaneg.xml");
		}
	}
}
